package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.PatriarchMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 家长端 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2023-04-27
 */
@Service
public class PatriarchServiceImpl extends ServiceImpl<PatriarchMapper, Patriarch> implements IPatriarchService {


    @Autowired
            @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IWecharsBindService iWecharsBindService;

    @Autowired
    @Lazy
    ITranscriptService iTranscriptService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    IWecharsPushLogService iWecharsPushLogService;

    @Autowired
    @Lazy
    ITranscriptSetService iTranscriptSetService;

    /**
     * 成绩推送
     */
    public void transcriptPush(){

        //Quarter quarter = iQuarterService.getNowQuarter();

        //quarter.setYearPart(2023);
        //quarter.setNum(2);
        //quarter.setAliasName("春季班");


        TranscriptSet transcriptSet = iTranscriptSetService.getById("1646797065822404608");

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(transcriptSet.getPatriarchYearPart(),transcriptSet.getPatriarchQuarterNum());


        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
        wecharsBindQueryWrapper.inSql("student_id","select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where b.year_class_id in(3,4,5,6,7,8,9) and a.status= 1 and a.reading_status in (1,5) and a.year_part = "+quarter.getYearPart()+" and a.quarter_num = "+quarter.getNum()+"");
       // wecharsBindQueryWrapper.inSql("student_id","select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where b.year_class_id in(6) and a.status= 1 and a.reading_status in(1,5) and a.year_part = "+quarter.getYearPart()+" and a.quarter_num = "+quarter.getNum()+"");//只推送初三

        //wecharsBindQueryWrapper.in("student_id",1624797515394056192L);
        //wecharsBindQueryWrapper.inSql("student_id","select student_id from order_detail where school_id = 1600457916720910338 and year_part = "+quarter.getYearPart()+" and quarter_num = "+quarter.getNum()+" ");
        //wecharsBindQueryWrapper.inSql("student_id","select student_id from transcript where year_part = 2023 and quarter_num = 2");


        //System.out.println("transcriptPush");
        List<WecharsBind> wecharsBindList = iWecharsBindService.list(wecharsBindQueryWrapper);
        for (WecharsBind wecharsBind:wecharsBindList){
            Integer pushCount = 3;//发送第四遍
            QueryWrapper<WecharsPushLog> wecharsPushLogQueryWrapper = new QueryWrapper<>();
            wecharsPushLogQueryWrapper.eq("openid",wecharsBind.getOpenid());
            wecharsPushLogQueryWrapper.eq("year_part",quarter.getYearPart());
            wecharsPushLogQueryWrapper.eq("quarter_num",quarter.getNum());
            wecharsPushLogQueryWrapper.eq("type",1);
            wecharsPushLogQueryWrapper.eq("count",pushCount);
            Long count = iWecharsPushLogService.count(wecharsPushLogQueryWrapper);
            if (count>0){
                UpdateWrapper<Transcript> transcriptUpdateWrapper = new UpdateWrapper<>();
                transcriptUpdateWrapper.eq("year_part",quarter.getYearPart());
                transcriptUpdateWrapper.eq("quarter_num",quarter.getNum());
                transcriptUpdateWrapper.eq("exam_num",transcriptSet.getPatriarchExamNum());
                transcriptUpdateWrapper.eq("student_id",wecharsBind.getStudentId());
                transcriptUpdateWrapper.set("is_wx_push",1);
                iTranscriptService.update(null,transcriptUpdateWrapper);
                continue;
            }

            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.inSql("id","select student_id from wechars_bind where openid = '"+wecharsBind.getOpenid()+"' ");
            wecharsBindQueryWrapper.inSql("id","select student_id from transcript where year_part = "+quarter.getYearPart()+" and quarter_num = "+quarter.getNum()+" and is_statistics = 0 and exam_num="+transcriptSet.getTeacherExamNum());//and year_class_id = 6 and exam_num=5
            studentQueryWrapper.groupBy("name");
            List<Student> studentList = iStudentService.list(studentQueryWrapper);
            StringBuilder stringBuilder = new StringBuilder();
            List<Long> studentIdList = new ArrayList<>();
            for (Student student:studentList){
                stringBuilder.append(student.getName()).append(",");
                studentIdList.add(student.getId());
            }
            /*if (wecharsBind.getOpenid().equals("oRIol5oemCb0ukQma_2UtRm_hjhA") || wecharsBind.getOpenid().equals("oRIol5iPFMLiXpwdAOlt821PsHHw")){

            }*/
            //System.out.println("开始推送");
            String url = "http://jz.5ixmy.xyz";
            if (stringBuilder.length() >0){
                stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
                StringBuilder first = new StringBuilder();
                first.append(stringBuilder.toString()+"家长，您好！请点击填写孩子本次学校考试的成绩");
                LocalDate currentDate = LocalDate.now();
                String keyword1 = String.valueOf(currentDate.getYear())+"年";
                StringBuilder keyword2 = new StringBuilder();
                keyword2.append(quarter.getAliasName());
                StringBuilder keyword3 = new StringBuilder();
                keyword3.append(stringBuilder.toString());
                StringBuilder remark = new StringBuilder();
                remark.append("如有疑问，请与老师联系");
                //List<String> opendIdList = iWecharsBindService.getSendOpenid(wecharsBind.getStudentId());
                List<String> opendIdList = new ArrayList<>();
                opendIdList.add(wecharsBind.getOpenid());
                iWecharsBindService.wxPushPartriach(opendIdList,first.toString(),keyword1,keyword2.toString(),keyword3.toString(),remark.toString(),url,String.valueOf(Math.random()));

                //添加到推送记录
                QueryWrapper<WecharsPushLog> wecharsPushLogQueryWrapperAdd = new QueryWrapper<>();
                wecharsPushLogQueryWrapperAdd.eq("year_part",quarter.getYearPart());
                wecharsPushLogQueryWrapperAdd.eq("quarter_num",quarter.getNum());
                wecharsPushLogQueryWrapperAdd.eq("type",1);
                wecharsPushLogQueryWrapperAdd.eq("openid",wecharsBind.getOpenid());
                wecharsPushLogQueryWrapperAdd.last(" limit 1");
                WecharsPushLog wecharsPushLog = iWecharsPushLogService.getOne(wecharsPushLogQueryWrapperAdd);
                if (wecharsPushLog == null){
                    wecharsPushLog = new WecharsPushLog();
                    wecharsPushLog.setId(idWorker.nextId());
                    wecharsPushLog.setAddDate(LocalDate.now());
                    wecharsPushLog.setYearPart(quarter.getYearPart());
                    wecharsPushLog.setQuarterNum(quarter.getNum());
                    wecharsPushLog.setContent(stringBuilder.toString());
                    wecharsPushLog.setRemark("成绩统计推送");
                    wecharsPushLog.setType(1);
                    wecharsPushLog.setCount(pushCount);
                    wecharsPushLog.setOpenid(wecharsBind.getOpenid());
                    iWecharsPushLogService.save(wecharsPushLog);
                }else {
                    wecharsPushLog.setCount(pushCount);
                    iWecharsPushLogService.updateById(wecharsPushLog);
                }

                UpdateWrapper<Transcript> transcriptUpdateWrapper = new UpdateWrapper<>();
                transcriptUpdateWrapper.eq("year_part",quarter.getYearPart());
                transcriptUpdateWrapper.eq("quarter_num",quarter.getNum());
                transcriptUpdateWrapper.eq("exam_num",5);
                transcriptUpdateWrapper.eq("student_id",wecharsBind.getStudentId());
                transcriptUpdateWrapper.set("is_wx_push",1);
                iTranscriptService.update(null,transcriptUpdateWrapper);
            }
        }
    }


    public void testPush(){

        String url ="http://www.baidu.com";

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("黄先生,");
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
        StringBuilder first = new StringBuilder();
        first.append(stringBuilder.toString()+"家长，您好！请点击填写孩子本次学校考试的成绩");
        LocalDate currentDate = LocalDate.now();
        String keyword1 = String.valueOf(currentDate.getYear())+"年";
        StringBuilder keyword2 = new StringBuilder();
        keyword2.append("第二学期");
        StringBuilder keyword3 = new StringBuilder();
        keyword3.append(stringBuilder.toString());
        StringBuilder remark = new StringBuilder();
        remark.append("如有疑问，请与老师联系");
        List<String> opendIdList = iWecharsBindService.getSendOpenid(1637353020809281536L);
        iWecharsBindService.wxPushPartriach(opendIdList,first.toString(),keyword1,keyword2.toString(),keyword3.toString(),remark.toString(),url,String.valueOf(Math.random()));

    }
}
